import React, { PureComponent } from 'react';
import { connect } from 'dva';
import LoadingWrapper from '../../components/LoadingWrapper';
import Card from './Card';

@connect(({ picture, loading }) => ({
  pictures: picture.pictures,
  loading: !!loading.effects['picture/fetchFavlist'],
}))
export default class Favorites extends PureComponent {
  componentDidMount() {
    this.getFavlist();
  }

  getFavlist = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'picture/fetchFavlist' });
  };

  handleDetail = pid => {
    const { history } = this.props;
    history.push(`/detail?pid=${pid}`);
  };

  handleUserIndex = uid => {
    const { history } = this.props;
    history.push(`/pic/user?uid=${uid}`);
  };

  render() {
    const { pictures, loading } = this.props;

    return (
      <LoadingWrapper loading={loading}>
        {pictures.length > 0 &&
          pictures.map(item => (
            <Card
              key={item.id}
              picInfo={item}
              onDetail={this.handleDetail}
              onSuccess={this.getFavlist}
              onUserIndex={this.handleUserIndex}
            />
          ))}
      </LoadingWrapper>
    );
  }
}
